import { obj_str, sendJson, CurModel } from '../../nui';

const getUrl = (v) => {
    const host = window.location.host;

    let pos = host.indexOf(":8088");
    if (pos > 0) {
        return "http://" + window.location.hostname + v;
    }

    pos = host.indexOf(":9000");
    if (pos > 0) {
        return "http://" + window.location.hostname + v;
    }

    return "http://" + window.location.host + v;
};

const is_debug = () => {
    if (process.env.NODE_ENV !== 'production') {
        return true;
    }

    return false;
};

const get_way = (url, port, cmd) => {
    const t = is_debug() ? `http://127.0.0.1:${port}/${cmd}` : getUrl(`/${cmd}`);
    if (url) {
        return t + "/" + url;
    }

    return t + url;
};

const scan_db = (data) => {
    let tab = obj_str(data, "n");
    if (!tab) {
        tab = obj_str(data, "tab");
    }

    if (tab) {
        const db = CurModel.get_db(tab);
        if (db) {
            data["db"] = db;
        }
    }

    return data;
};

const urlTb = (fnDone, url, data, okfun=null, errfun=null) => {
    const cmd = scan_db(data);
    sendJson(get_way(url, 9983, "timedb"), cmd, okfun, errfun, fnDone);
};

export {getUrl, urlTb, get_way, is_debug};
